import re
from datetime import datetime, timedelta

from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from user.models import User, VerifyCode


class SmsSerializer(serializers.Serializer):
    phone = serializers.CharField(required=True, max_length=11, min_length=11, error_messages={
        'max_length': '手机号11位',
        'min_length': '手机号11位',
    })

    def validate_phone(self, phone):
        # 验证手机号有没有注册过
        if User.objects.filter(phone=phone).exists():
            raise serializers.ValidationError('此手机号已注册')
        if not re.match(r'1\d{10}', phone):
            raise serializers.ValidationError('手机号格式错误')
        return phone


class RegisterSerializer(serializers.ModelSerializer):
    code = serializers.CharField(required=True, max_length=4, min_length=4, error_messages={
        'required': '必需输入验证码',
        'max_length': '验证码4位',
        'min_length': '验证码4位'
    }, write_only=True)

    # 用户名验证方法一种
    username = serializers.CharField(required=True, allow_blank=False,
                                     validators=[UniqueValidator(queryset=User.objects.all(), message='此用户名已被占用')])

    repassword = serializers.CharField(write_only=True, style={'input_type': 'password'})

    class Meta:
        model = User
        fields = ['username', 'password', 'repassword', 'phone', 'code']

    def validate_code(self, code):
        # 验证码确认
        verifycodes = VerifyCode.objects.filter(phone=self.initial_data['phone']).order_by('update_time')
        if verifycodes:
            verifycode = verifycodes.first()
            # 设置一个过期时间，现在的时间减去有效时间
            time_delta = datetime.now() - timedelta(minutes=10)
            if time_delta > verifycode.update_time:
                raise serializers.ValidationError('验证码过期，请重新发送')
            if verifycode.code != code:
                raise serializers.ValidationError('验证码错误')
        else:
            raise serializers.ValidationError('请发送验证码')
        return code

    def validate(self, attrs):
        # 验证两次密码是否一致
        if attrs['password'] != attrs['repassword']:
            raise serializers.ValidationError('密码不一致')
        # 确认密码和验证码不放入数据库，先删掉再创建用户
        del attrs['repassword']
        del attrs['code']
        return attrs


    # def validate_username(self, username):
    #     # 验证用户名是否重复的一种方法
    #     if User.objects.filter(username=username).exists():
    #         raise serializers.ValidationError('此用户名已注册')
    #     return username

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'password', 'phone']